/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cxhd.dc.controller;

import com.cxhd.dc.DataConfig;
import com.cxhd.dc.tool.DbTool;
import com.cxhd.dc.tool.FileUtil;
import com.cxhd.dc.tool.Tools;
import com.cxhd.dc.tool.ZipFileTool;
import com.google.common.io.Files;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class PatientController extends Controller {

    public void index() {
        render("/patient/patientList.jsp");
    }

    public void getPatientList() {

        String sql = "select a.pk,pat_id,b.pat_name,pat_sex,pat_birthdate ,a.mods_in_study,a.created_time,a.num_series,a.num_instances";
        String serarchContent = getPara("content", null);
        String param = "from study a LEFT JOIN patient b on a.patient_fk=b.pk order by a.created_time desc";
        if (serarchContent != null) {
            param = "from study a LEFT JOIN patient b on a.patient_fk=b.pk where b.pat_name like '%" + serarchContent + "%' or b.pat_id like '%" + serarchContent + "%' order by a.created_time desc";

        }

        Page<Record> userPage = Db.use("pacsio").paginate(getParaToInt("currentPage"), getParaToInt("pageSize", 10), sql, param);

        renderJson(userPage);
    }

    public void sendCenter() {
        String pks = getPara("pks");
        if (pks != null) {
            List<File> listfile = new ArrayList<File>();
            List<Record> list = Db.use("pacsio").find("SELECT c.sop_iuid, d.filepath,e.dirpath,a.study_iuid FROM study a LEFT JOIN series b on b.study_fk=a.pk LEFT JOIN instance c ON c.series_fk= b.pk LEFT JOIN files d on d.instance_fk=c.pk LEFT JOIN filesystem e ON e.pk=d.filesystem_fk WHERE a.pk in(" + pks + ")");
            List<String> studyList = new ArrayList<String>();
            if (list != null && !list.isEmpty()) {
                System.out.println("" + list.size() + list.get(0).getColumns());
                for (Record re : list) {
                    if (!studyList.contains(re.getStr("study_iuid"))) {
                        studyList.add(re.getStr("study_iuid"));
                    }
                    try {
                        File newFile = new File(DataConfig.getInstance().getBasePath() + "/" + DataConfig.getInstance().getOtherFileFolder() + re.getStr("sop_iuid") + ".dcm");
                        System.out.println(newFile.getAbsoluteFile() + "------------------" + (re.getStr("dirpath") + "/" + re.getStr("filepath")).replace("\\", "/"));
                        Files.copy(new File((re.getStr("dirpath") + "/" + re.getStr("filepath")).replace("\\", "/")), newFile);
                        listfile.add(newFile);
                        String zipName = DataConfig.getInstance().getSN().toUpperCase() + "_" + newFile.getName() + "_" + DataConfig.getInstance().getLocalhostSN() + ".u";

                        String zipPath = DataConfig.getInstance().getBasePath() + "/" + DataConfig.getInstance().getZipFolder() + zipName;
                        String password = FileUtil.makePSWD(zipName.substring(0, zipName.lastIndexOf(".")));
                        ZipFileTool.upZipFile(newFile, zipPath, password, true, zipPath);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                //压缩报告文件sql文件
                if ("client".equalsIgnoreCase(PropKit.get("serverType"))) {
                    if (studyList != null && !studyList.isEmpty()) {
                        for (String iuid : studyList) {
                            //查看是否有报告
                            //查询moreprt表
                            String sqlFile = "";
                            sqlFile = DbTool.makeInsertSqlInsert(Db.use("dcmris_en").findFirst("select * from morerpt where rpt_study_iuid='" + iuid + "'"), "morerpt","replace into ");
                            //查询morerpt_history
                            List<Record> listSql = Db.use("dcmris_en").find("select * from morerpt_history where rpt_study_iuid='" + iuid + "' ");

                            for (Record rd : listSql) {
                                sqlFile = sqlFile==null?"":"`;`";
                                sqlFile += DbTool.makeInsertSqlInsert(rd, "morerpt_history","insert into ");
                            }
                            // System.out.println(sqlFile+"--------------------------");
                            if (sqlFile != null && !"".equalsIgnoreCase(sqlFile)) {
                                File sqlFiles = new File(DataConfig.getInstance().getBasePath() + "/" + DataConfig.getInstance().getOtherFileFolder() + iuid + ".sql");
                                FileUtil.writeText(DataConfig.getInstance().getBasePath() + "/" + DataConfig.getInstance().getOtherFileFolder() + iuid + ".sql", sqlFile);
                                String zipName = DataConfig.getInstance().getSN().toUpperCase() + "_" + sqlFiles.getName() + "_" + DataConfig.getInstance().getLocalhostSN() + ".u";

                                String zipPath = DataConfig.getInstance().getBasePath() + "/" + DataConfig.getInstance().getZipFolder() + zipName;
                                String password = FileUtil.makePSWD(zipName.substring(0, zipName.lastIndexOf(".")));
                                ZipFileTool.upZipFile(sqlFiles, zipPath, password, true, zipPath);
                            }
                            //压缩rpt文件

                            File search_rpt[] = new File("K:/reports/" + iuid + "/").listFiles();
                            for (File rpt : search_rpt) {
                                if (rpt.getName().endsWith(".rpt")) {
                                    try {
                                        File newRptFile = new File(DataConfig.getInstance().getBasePath() + "/" + DataConfig.getInstance().getOtherFileFolder() + DataConfig.getInstance().getSN().toUpperCase() + "-" + iuid + "-" + rpt.getName());
//                      
                                        Files.copy(rpt, newRptFile);

                                        String zipName = DataConfig.getInstance().getSN().toUpperCase() + "_" + newRptFile.getName() + "_" + DataConfig.getInstance().getLocalhostSN() + ".u";

                                        String zipPath = DataConfig.getInstance().getBasePath() + "/" + DataConfig.getInstance().getZipFolder() + zipName;
                                        String password = FileUtil.makePSWD(zipName.substring(0, zipName.lastIndexOf(".")));
                                        ZipFileTool.upZipFile(newRptFile, zipPath, password, true, zipPath);
                                        break;
                                    } catch (IOException ex) {

                                    }
                                }
                            }
                        }
                    }
                }

                renderText("true");
            } else {
                renderText("false");
            }

        }
    }

    public void sendOther() {
        try {
            String filePath = getPara("filePath");
            String target = getPara("target", DataConfig.getInstance().getSN()).toUpperCase();
            File f = new File(filePath);
            System.out.println(f.getAbsolutePath() + "" + f.exists());
            if (f.isFile()) {
                String zipName = target + "_" + f.getName() + "_" + DataConfig.getInstance().getLocalhostSN() + ".u";

                String zipPath = DataConfig.getInstance().getBasePath() + "/" + DataConfig.getInstance().getZipFolder() + zipName;
                String password = FileUtil.makePSWD(zipName.substring(0, zipName.lastIndexOf(".")));
                ZipFileTool.upZipFile(f, zipPath, password, true, zipPath);

                renderText("true");
            } else {
                System.out.println("不是文件类型");
                renderText("false");
            }
        } catch (Exception e) {

            e.printStackTrace();
            renderText("false");
        }

    }

    public void getRecvicetList() {

        String sql = "select * ";
        String serarchContent = getPara("content", null);
        String param = "from logstudy order by createtime desc";
        if (serarchContent != null) {
            param = "from logstudy pat_name like '%" + serarchContent + "%' or pat_id like '%" + serarchContent + "%' order by a.createtime desc";

        }

        Page<Record> userPage = Db.use("dcmris_en").paginate(getParaToInt("currentPage"), getParaToInt("pageSize", 10), sql, param);
        List<Record> list = userPage.getList();
        List<Record> newlist = new ArrayList<Record>();

        for (Record re : list) {
            String path = DataConfig.getInstance().getBasePath() + "/" + DataConfig.getInstance().getLogStudyFolder() + "/" + re.getStr("study_iuid") + ".properties";
            System.out.println(path);
            Properties prop = new Properties();

            try {
                prop.load(new FileInputStream(path));
                re.set("other2", prop.getProperty("update"));
                newlist.add(re);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Page<Record> userPage2 = new Page<Record>(newlist, userPage.getPageNumber(), userPage.getPageSize(), userPage.getTotalPage(), userPage.getTotalRow());
        renderJson(userPage2);
    }

    public void recvice() {
        render("/patient/recviceList.jsp");
    }
}
